package com.example.repair_service.service.impl;

import com.example.repair_service.constant.MessageConstant;
import com.example.repair_service.constant.StatusConstant;
import com.example.repair_service.dto.UserDTO;
import com.example.repair_service.dto.UserLoginDTO;
import com.example.repair_service.entity.UserEntity;
import com.example.repair_service.exception.AccountLockedException;
import com.example.repair_service.exception.AccountNotFoundException;
import com.example.repair_service.exception.PasswordErrorException;
import com.example.repair_service.mapper.UserMapper;
import com.example.repair_service.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public UserEntity login(UserLoginDTO userLoginDTO)  {
        String mobile = userLoginDTO.getMobile();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        UserEntity user = userMapper.getByMobile(mobile);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }



        //3、返回实体对象
        return user;
    }

    @Override
    public void register(UserDTO userDTO) {
        UserEntity user=new UserEntity();
        BeanUtils.copyProperties(userDTO,user);
        user.setStatus(StatusConstant.ENABLE);
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        userMapper.register(user);

    }
}
